package com.yjzx.util.service.aop.login;

import com.yjzx.util.common.util.HttpServletUtils;
import com.yjzx.util.common.util.encrypt.JwtUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author jiangliang
 * @describe 登录拦截器
 * @dateTime 2019/6/14 13:57
 **/
public class LoginInterceptor extends HandlerInterceptorAdapter {


    private static Set<String> notNeedLogin;

    static {
        notNeedLogin = new LinkedHashSet<>();
        //登录接口
        notNeedLogin.add("/user/login");

    }

    /**
     * 请求到达时执行
     * @param request
     * @param response
     * @param handler
     * @return true 代表不拦截  false 代表拦截不执行后面的代码
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        //无需认证，直接通过
        if(notNeedLogin.contains(uri)||uri.contains("/error")||uri.contains("/404")){
            return true;
        }

        //用户未登录 直接调至登录界面
        if(getUser() == null){
            throw new RuntimeException("未登录！");
        }
        return true;
    }

    private Object getUser() {
        HttpServletUtils.getRequest().getSession().getAttribute("user_info");
        JwtUtil.validateAccessToken(HttpServletUtils.getRequest());
        return null;
    }

    /**
     * 请求执行后执行  返回视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 返回已经处理后执行 用于清理资源或者记录日志等
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * controller返回值是java.util.concurrent.Callable时才会调用该方法并使用新线程运行
     * @param request
     * @param response
     * @param handler
     * @throws Exception
     */
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
